import { Controller } from 'egg';

export default class UsersController extends Controller {
  public async index() {
    const { ctx } = this;
    ctx.body = await ctx.service.test.sayHi('egg');
  }
  public async login() {
    const { ctx } = this;
    const {username, password} = ctx.request.body;
    
    const user = await ctx.service.users.login(password, undefined, username);
    // 登录失败
    if (user === null){
      ctx.body = {
        code: 1,
        message: "用户名或密码错误"
      };
      return ;
    }
    // 登录成功
    ctx.session.user_id = user?.user_id;
    ctx.body = {
      code: 0,
      message: "登录成功",
      result: user
    }
  }
  public async modifyPassword (){
    const { ctx } = this;
    const {id} = ctx.params;
    const {password, new_password} = ctx.request.body;
    
    // 输入了空参数
    if(id===undefined || password===undefined || new_password===undefined){
      ctx.status = 400;
      ctx.body = {
        code: 1,
        message: "输入参数错误，结果返回了{需要键值:输入值}",
        result:{
          id,
          password,
          new_password,
        }
      }
      return;
    }
    // 校验新密码是否符合规范
    if (!ctx.service.users.validatePassword(new_password)) {
      ctx.status = 400;
      ctx.body = {
        code: 1,
        message: "输入的新密码不符合规则，请输入5~24位的数字，字母，下划线组合"
      }
      return;
    }
    // 检验旧密码是否正确
    // 准备就绪，更新密码
    const changedRows = await ctx.service.users.update({password:new_password},{id});
    if (changedRows>0){
      ctx.body = {
        code: 0,
        message: "更新密码成功"
      }  
    } else{
      ctx.body = {
        code: 0,
        message: "更新密码成功，但密码没有改变"
      }
    }
  }
  // public async hasLogin (){
  //   if (isNaN(this.ctx.session.user_id)){
      
  //   }
  //   else ({})
  // }
}
